import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; import { prisma } from '@/lib/prisma'; interface RouteParams { params: Promise<{ id: string; }>; } // PUT - Actualizar sección export async function PUT(request: NextRequest, { params }: RouteParams) { try { const session = await getServerSession(authOptions); if (!session || session.user.role !== 'ADMIN') { return NextResponse.json( { message: 'No autorizado' }, { status: 401 } ); } const { id } = await params; const body = await request.json(); const { name, classId } = body; // Verificar si la sección existe const existingSection = await prisma.section.findFirst({ where: { id, deletedAt: null, }, }); if (!existingSection) { return NextResponse.json( { message: 'Sección no encontrada' }, { status: 404 } ); } // Validaciones básicas if (!name || !classId) { return NextResponse.json( { message: 'Nombre y clase son requeridos' }, { status: 400 } ); } // Verificar si la clase existe const classExists = await prisma.class.findFirst({ where: { id: classId, deletedAt: null, }, include: { period: { select: { isActive: true, }, }, }, }); if (!classExists) { return NextResponse.json( { message: 'La clase seleccionada no existe' }, { status: 400 } ); } if (!classExists.period.isActive) { return NextResponse.json( { message: 'No se puede actualizar una sección para una clase de un periodo inactivo' }, { status: 400 } ); } // Verificar si ya existe otra sección con el mismo nombre para la misma clase if (name !== existingSection.name || classId !== existingSection.classId) { const duplicateSection = await prisma.section.findFirst({ where: { name, classId, deletedAt: null, id: { not: id }, }, }); if (duplicateSection) { return NextResponse.json( { message: 'Ya existe otra sección con este nombre para la clase seleccionada' }, { status: 400 } ); } } // Actualizar sección await prisma.section.update({ where: { id }, data: { name, classId, }, }); return NextResponse.json( { message: 'Sección actualizada exitosamente' }, { status: 200 } ); } catch (error) { console.error('Error updating section:', error); return NextResponse.json( { message: 'Error interno del servidor' }, { status: 500 } ); } } // DELETE - Eliminar sección (soft delete) export async function DELETE(request: NextRequest, { params }: RouteParams) { try { const session = await getServerSession(authOptions); if (!session || session.user.role !== 'ADMIN') { return NextResponse.json( { message: 'No autorizado' }, { status: 401 } ); } const { id } = await params; // Verificar si la sección existe const existingSection = await prisma.section.findFirst({ where: { id, deletedAt: null, }, include: { _count: { select: { teacherAssignments: true, studentEnrollments: true, }, }, }, }); if (!existingSection) { return NextResponse.json( { message: 'Sección no encontrada' }, { status: 404 } ); } // Verificar si la sección tiene asignaciones de profesores o inscripciones de estudiantes if (existingSection._count.teacherAssignments > 0 || existingSection._count.studentEnrollments > 0) { return NextResponse.json( { message: 'No se puede eliminar una sección que tiene profesores asignados o estudiantes inscritos' }, { status: 400 } ); } // Realizar soft delete await prisma.section.update({ where: { id }, data: { deletedAt: new Date(), }, }); return NextResponse.json( { message: 'Sección eliminada exitosamente' }, { status: 200 } ); } catch (error) { console.error('Error deleting section:', error); return NextResponse.json( { message: 'Error interno del servidor' }, { status: 500 } ); } }